package com.sys.controller;

import com.sys.dto.JwtResponse;
import com.sys.dto.LoginRequest;
import com.sys.dto.RegisterRequest;
import com.sys.service.AuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器，处理用户登录请求
 */
@RestController
@CrossOrigin
@RequestMapping("/auth")
@Api(tags = "认证管理")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 用户登录接口
     *
     * @param loginRequest 包含用户名和密码的登录请求
     * @return 包含 JWT 的响应实体
     * @throws Exception 如果认证失败
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "使用MD5加密的密码进行登录验证\n\n" +
            "示例请求体:\n" +
            "{\n" +
            "  \"username\": \"13800138001\",\n" +
            "  \"password\": \"12345\"\n" +
            "}\n\n" +
            "数据库中的密码已经是MD5加密后的值，不需要客户端额外处理")
    public ResponseEntity<JwtResponse> createAuthenticationToken(@Validated @RequestBody LoginRequest loginRequest)
            throws Exception {
        return ResponseEntity.ok(authService.login(loginRequest));
    }

    /**
     * 用户注册接口
     *
     * @param registerRequest 包含用户名、密码、用户类型、姓名的注册请求
     * @return 响应实体
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "注册新用户。\n\n示例请求体：\n{\n  \"username\": \"13800138001\",\n  \"password\": \"123456\",\n  \"userType\": \"therapist\",\n  \"name\": \"张三\"\n}")
    public ResponseEntity<?> registerUser(@Validated @RequestBody RegisterRequest registerRequest) {
        authService.register(registerRequest);
        return ResponseEntity.ok("用户注册成功");
    }
}